package com.lianyi.gaodeapi

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.*
import kotlinx.android.synthetic.main.activity_map.*
import java.net.MalformedURLException
import java.net.URL


class MapActivity : AppCompatActivity() {
    var aMap: AMap? = null
    var tyoe = 1;
    var marker: Marker? = null
    var marker2: Marker? = null

    //线路
    val latLngs: MutableList<LatLng> = ArrayList()
    val markerList: MutableList<Marker> = ArrayList()
    val markerList2: MutableList<Marker> = ArrayList()
    var polyline: Polyline? = null

    //绘制直线
    var polygonOptions: PolygonOptions? = null
    var polygon: Polygon? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_map)
        mMapView.onCreate(savedInstanceState)
        initaMap()
        viewClick()
    }


    fun initaMap() {
        aMap = mMapView.map
        val myLocationStyle: MyLocationStyle = MyLocationStyle() //初始化定位蓝点样式类
        //初始化定位参数
        // 连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        //myLocationStyle.interval(2000) //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeColor(Color.TRANSPARENT);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap?.myLocationStyle = myLocationStyle //设置定位蓝点的Style
//        aMap.uiSettings.isMyLocationButtonEnabled = true;//设置默认定位按钮是否显示，非必需设置。
//        aMap.uiSettings.isMyLocationButtonEnabled = true;//设置默认定位按钮是否显示，非必需设置。
        aMap?.isMyLocationEnabled = true // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        // myLocationStyle.showMyLocation(false)
        aMap?.addOnMyLocationChangeListener() {
            val lat = it.latitude
            val lon = it.longitude
            Log.i("asd", "lat=$lat lon= $lon")
        }
        aMap?.moveCamera(
            CameraUpdateFactory.newCameraPosition(
                CameraPosition(
                    LatLng(
                        0.0,
                        0.0
                    ), 15f, 0f, 0f
                )
            )
        )
        addGeoServer()

        //地图点击事件
        aMap?.addOnMapClickListener {
            val lat = it.latitude
            val lon = it.longitude
            when (tyoe) {
                1 -> {
                    //绘制点 就应该只有一个坐标  当marker存在时 需要移除掉上一个
                    if (marker != null) {
                        marker?.remove()
                    }
                    marker = aMap?.addMarker(MarkerOptions().position(LatLng(lat, lon)))
                }
                2 -> {//绘制直线
                    marker2 = aMap?.addMarker(MarkerOptions().position(LatLng(lat, lon)))
                    latLngs.add(LatLng(lat, lon))//记录每个点位
                    markerList.add(marker2!!)
                }

                3 -> {
                    marker2 = aMap?.addMarker(MarkerOptions().position(LatLng(lat, lon)))
                    polygonOptions?.add(LatLng(lat, lon))
                    markerList2.add(marker2!!)
                }
            }
            Log.i("asd", "当前选中的位置   lat=$lat lon= $lon")
        }


    }


    fun addGeoServer() {
        val tileProvider = object : UrlTileProvider(256, 256) {
            override fun getTileUrl(x: Int, y: Int, zoom: Int): URL? {
//                Log.i("asasasa", "$x  $y  $zoom")
                val url = "https://webst01.is.autonavi.com/appmaptile?x=$x&y=$y&z=$zoom&style=6"
                try {
                    return URL(String.format(url, x, y, zoom))
                } catch (e: MalformedURLException) {
                    e.printStackTrace();
                }
                return null
            }
        }
        aMap?.addTileOverlay(
            TileOverlayOptions()
                .tileProvider(tileProvider)
                .diskCacheEnabled(true)
                .diskCacheSize(50000)
                .diskCacheDir("/storage/emulated/0/amap1/OMCcache")
                .memoryCacheEnabled(false)
                .memCacheSize(10000)
                .zIndex(10f)
        )
    }


    fun viewClick() {
        btnMarker.setOnClickListener {
            tyoe = 1
            textview.text = "当前绘制: 点"
        }
        btnPolyline.setOnClickListener {
            tyoe = 2
            textview.text = "当前绘制: 直线"
        }
        btnpolygonOptions.setOnClickListener {
            tyoe = 3
            textview.text = "当前绘制: 面"
            polygonOptions = PolygonOptions()

        }

        remove.setOnClickListener {
            when (tyoe) {
                1 -> {
                    marker?.remove()
                }
                2 -> {
                    tyoe = 1
                    polyline?.remove()
                    latLngs.clear()
                }
                3 -> {
                    tyoe = 1
                    polygon?.remove()
                    polygonOptions = null
                }
            }
            textview.text = "当前绘制:点"
        }
        link.setOnClickListener {
            when (tyoe) {
                2 -> {
//                    addGeoServer()
//                    aMap?.clear(true)
                    for (i in 0 until markerList.size) {
                        markerList[i].remove()
                    }
                    polyline = aMap?.addPolyline(
                        PolylineOptions().addAll(latLngs).width(10f)
                            .setDottedLine(false) // 关闭虚线
                            .geodesic(true)
                            .color(Color.argb(235, 1, 180, 247)).zIndex(999f)
                    )
//                    aMap?.addPolyline(PolylineOptions().addAll(latLngs).width(10f).color(Color.argb(235, 1, 180, 247)).zIndex(999f))
                }
                3 -> {
//                    addGeoServer()
//                    aMap?.clear(true)
                    markerList2.forEach {
                        it.remove()
                    }
                    polygonOptions?.strokeWidth(5f) // 多边形的边框
                        ?.strokeColor(Color.argb(235, 1, 180, 247)) // 边框颜色
                        ?.fillColor(Color.argb(235, 255, 0, 0))?.zIndex(999f)   // 多边形的填充色
                    if (polygonOptions != null) {
                        polygon = aMap?.addPolygon(polygonOptions)
                    }
                }

            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        mMapView.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        mMapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause()
    }

}